<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>使用request封装ajax请求参数</title>
  </head>
  <body>
    <button onclick="testGet()">发送GET请求</button><br />
    <button onclick="testPost()">发送POST请求</button><br />
    <button onclick="testPut()">发送PUT请求</button><br />
    <button onclick="testDelete()">发送Delete请求</button><br />

    <script>
      function axios({ url, method = "GET", params = {}, data = {} }) {
        return new Promise((resolve, reject) => {
          // 处理method
          method = method.toLocaleUpperCase();

          // 处理url参数并凭借到url中
          let queryString = "";
          Object.keys(params).forEach((key) => {
            queryString += `${key}=${params[key]}&`;
          });
          if (queryString) {
            // substring()： 本身不会改变原数据，需要重新赋值
            queryString = queryString.substring(0, queryString.length - 1);
            url += "?" + queryString;
          }

          // 1. 执行异步ajax请求
          // 创建xhr对象
          const request = new XMLHttpRequest();
          // 打开连接（初始化请求，没有请求）
          request.open(method, url, true); // true异步， false同步
          // 发送请求
          if (method === "GET" || method === "DELETE") {
            request.send();
          } else if (method === "POST" || method === "PUT") {
            // 发送json格式的data, 需要指定请求体格式类型
            request.setRequestHeader(
              "Content-type",
              "application/json; chartset=utf-8"
            );
            request.send(JSON.stringify(data));
          }

          // 接受请求
          request.onreadystatechange = () => {
            // 如果请求没有完成，直接结束
            if (request.readyState !== 4) {
              return;
            }

            // 如果响应状态码在[200, 300)之间代表成功，否则失败
            const { status, statusText } = request;
            if (status >= 200 && status < 300) {
              let response = {
                data: JSON.parse(request.response),
                status,
                statusText,
              };
              resolve(response);
            } else {
              reject(new Error("request error status is:" + status));
            }
          };
        });
      }

      function testGet() {
        axios({
          url: "http://localhost:3000/posts",
          method: "GET",
          params: {
            _start: 1,
            _end: 3,
            _limit: 2,
          },
        })
          .then((response) => console.log(response))
          .catch((err) => console.log(err));
      }

      function testPost() {
        axios({
          url: "http://localhost:3000/posts",
          method: "POST",
          data: {
            id: 6,
            title: "json-server6",
            author: "typicode6",
          },
        })
          .then((response) => console.log(response))
          .catch((err) => console.log(err));
      }

      function testPut() {
        axios({
          url: "http://localhost:3000/posts/1",
          method: "PUT",
          data: {
            title: "json-server6",
            author: "typicode6",
          },
        })
          .then((response) => console.log(response))
          .catch((err) => console.log(err));
      }

      function testDelete() {
        axios({
          url: "http://localhost:3000/posts/6",
          method: "DELETE",
        })
          .then((response) => console.log(response))
          .catch((err) => console.log(err));
      }
    </script>
  </body>
</html>
